<?php
class UserController extends CommonController {
	public function index() {
		if(!isset($_SESSION['user']['openid'])){
			$this->redirect('login');
		}
		$_user=M('User')->where("openid='{$_SESSION['user']['openid']}'")->find();
		if(empty($_user)){
			$this->redirect('login');
		}
		$_SESSION['user']=$_user;
		$user = is_user ( $_SESSION['user']['tel'] );
		$this->assign('user',$user);
		$webChat = new WebChat ();
		$ticket=$webChat->get_ticket();
		$noncestr=create_guid();
		$this->assign('noncestr',$noncestr);
		$signature="jsapi_ticket={$ticket}&noncestr={$noncestr}&timestamp={$_SERVER['REQUEST_TIME']}&url=http://{$_SERVER['HTTP_HOST']}".U('User/index');
		$this->assign('signature',sha1($signature));
		$this->display ();
	}
	public function login() {
		if ($this->isGet ()) {
			$this->display ();
		} else {
			$phone = trim ( $_POST ['phone'] );
			$code = trim ( $_POST ['code'] );
			if ($code != $_SESSION ['code']) {
				$rs ['status'] = 2;
				$rs ['msg'] = '验证码不正确';
				exit ( json_encode ( $rs ) );
			}
			$user = is_user ( $phone );
			if ($user['status']==1) {
				$_SESSION['user']['username']=$user['username'];
				$_SESSION['user']['card']=$user['card'];
			}else{
				$webChat=new WebChat();
				$user=$webChat->get_user_info($_SESSION['user']['openid']);
				$_SESSION['user']['username']=$user['nickname'];
				$maxUser=M('User')->field('card')->order('card desc')->find();
				$start_card=900001;
				if(empty($maxUser)){
					$card=$start_card;
				}else if(intval($maxUser['card'])<$start_card){
					$card=$start_card;
				}else{
					$card=intval($maxUser['card'])+1;
					if(substr($card)==4||substr($card,-1)==7){
						++$card;
					}
				}
				$_SESSION['user']['card']=$card;
			}
			$_SESSION['user']['tel']=$phone;
			$_SESSION['user']['create_time']=$_SERVER['REQUEST_TIME'];
			$user=M('User')->where("tel='{$phone}'")->find();
			$_SESSION['user']['binding_time']=$_SERVER['REQUEST_TIME'];
			if(empty($user)){
				$id=M('User')->save($_SESSION['user']);
				$_SESSION['user']['id']=$id;
			}else{
				$_SESSION['user']['id']=$user['id'];
				$_SESSION['user']['bonus']=$user['bonus'];
				M('User')->update($_SESSION['user']);
			}
			unset ( $_SESSION ['code'] );
			$rs ['status'] = 1;
			echo json_encode ( $rs );
		}
	}
	public function sendSms() {
		$phone = $_GET ['phone'];
		$time = strtotime ( date ( 'Y-m-d' ) );
		$count = M ( 'SmsLog' )->where ( "phone='{$phone}' and create_time>={$time}" )->count ();
		if ($count >= 10) {
			$rs ['status'] = 2;
			$rs ['msg'] = '今天你能使用的短信已经用完,请明天再来';
			exit ( json_encode ( $rs ) );
		}
		$data ['phone'] = $phone;
		$_SESSION ['code'] = $data ['code'] = String::randString(4,1);
		if(Sms::sendMsg($phone,$data['code'])){
			$data ['create_time'] = $_SERVER ['REQUEST_TIME'];
			M('SmsLog')->save($data);
			$rs ['status'] = 1;
		}else{
			$rs['status']=3;
			$rs['msg']='发送短信失败';
		}
		echo json_encode ( $rs );
	}
}